package com.xy.xymall.order.web;

import com.xy.common.exception.NoStockException;
import com.xy.xymall.order.service.OrderService;
import com.xy.xymall.order.vo.OrderConfirmVo;
import com.xy.xymall.order.vo.OrderSubmitVo;
import com.xy.xymall.order.vo.SubmitOrderRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

/**
 * @author XY
 * @version 1.0
 * @date 2020/11/23 12:47
 * @Description
 */
@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    /**
     * @param model
     * @author XY
     * @date 2021/1/14 10:30
     * @Description 进入结算页
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model){
        OrderConfirmVo orderConfirmVo= null;
        try {
            orderConfirmVo = orderService.confirmOrder();
            model.addAttribute("data",orderConfirmVo);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //展示订单数据
        return "confirm";
    }

    /**
     * @param vo
     * @author XY
     * @date 2021/1/21 9:56
     * @Description 下单功能
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes){
        try{
            SubmitOrderRespVo respVo=orderService.submitOrder(vo);
            if(respVo.getCode()==0){
                //下单成功来到支付页
                model.addAttribute("submitOrderResp",respVo);
                return "pay";
            }else{
                String msg="下单失败：";
                switch (respVo.getCode()) {
                    case 1: {
                        msg+="订单信息过期，请重新提交。";
                        break;
                    }
                    case 2: {
                        msg+="订单商品价格发生变化，请确认后提交。";
                        break;
                    }
                    case 3: {
                        msg+="库存锁定失败，商品库存不足。";
                        break;
                    }
                }
                redirectAttributes.addFlashAttribute("msg",msg);
                return "redirect:http://order.xymall.com/toTrade";
            }
        }catch (Exception e){
            if(e instanceof NoStockException){
                String message = ((NoStockException) e).getMessage();
                redirectAttributes.addFlashAttribute("msg",message);
            }
            return "redirect:http://order.xymall.com/toTrade";

        }
    }


}
